package com.suixun.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.authority.dao.AuthUserDataDao;
import com.authority.service.AuthUserDataService;
import com.suixun.dao.SchoolDiscountsMapper;
import com.suixun.dao.SchoolinfoMapper;
import com.suixun.dao.StdTeacherInfoMapper;
import com.suixun.dao.devicemanage.WorkspaceServiceDAO;
import com.suixun.entity.SchoolDiscounts;
import com.suixun.entity.SchoolDiscountsExample;
import com.suixun.entity.Schoolinfo;
import com.suixun.entity.SchoolinfoExample;
import com.suixun.entity.SchoolinfoExample.Criteria;
import com.suixun.entity.StatDeviceInfo;
import com.suixun.entity.StdTeacherInfo;
import com.suixun.entity.StdTeacherInfoExample;
import com.suixun.entity.form.ParamForm;
import com.suixun.exception.OpServiceException;
import com.suixun.service.WorkspaceService;
import com.suixun.util.DateUtil;
import com.suixun.util.SortListUtil;
import com.suixun.util.StringUtil;
import com.suixun.vo.WorkSpaceVO;

import rop.thirdparty.org.apache.commons.lang3.StringUtils;


@Service
public class WorkspaceServiceImpl implements WorkspaceService {

	@Resource
	private WorkspaceServiceDAO workspacedao;
	@Resource
	private AuthUserDataService authOrganDataService;
	@Resource
	private AuthUserDataDao authUserDataDao;
	@Resource
	private SchoolinfoMapper schoolinfoMapper;
	@Resource
	private SchoolDiscountsMapper schoolDiscountsMapper;
	@Resource
	private StdTeacherInfoMapper stdTeacherInfoMapper;
	
	@Override
	public List<StatDeviceInfo> statTotalDevice(ParamForm paramForm) {
		
		Map<String,Object> map = new HashMap<>();
		map.put("peopletel", paramForm.getPeopletel());
		map.put("schoolname", paramForm.getSchoolname());
		map.put("province", paramForm.getProvince());
		map.put("city", paramForm.getCity());
		map.put("town", paramForm.getTown());
		map.put("startdate", paramForm.getStartdate());
		map.put("enddate", paramForm.getEnddate());
		if(paramForm.getUserid() != null){
			map.put("userid", paramForm.getUserid());
			map.put("organ", true);
		}
		
		//获取设备总量统计
		List<StatDeviceInfo> totalList = workspacedao.getTotalDeivceList(map);
		//获取激活量统计
		List<StatDeviceInfo> activeList = workspacedao.getActiveDeviceList(map);
		//获取缴费量统计
		List<StatDeviceInfo> paymentList = workspacedao.getPaymentDeviceList(map);
		if (totalList.size() > 0) {
			for (StatDeviceInfo totalTemp : totalList) {
				if (totalTemp.getDevicetype() != null) {
					switch (totalTemp.getDevicetype()) {
					case 1:
						totalTemp.setDevicetypename("手表");
						break;
					case 2:
						totalTemp.setDevicetypename("智能学生证");
						break;
					case 3:
						totalTemp.setDevicetypename("考勤卡");
						break;
					case 8:
						totalTemp.setDevicetypename("13.56");
						break;
					case 9:
						totalTemp.setDevicetypename("2.4");
						break;
					}
				}
				if (activeList.size() > 0) {
					for (StatDeviceInfo activeTemp : activeList) {
						if (String.valueOf(totalTemp.getDevicetype()).equals(String.valueOf(activeTemp.getDevicetype()))) {
							totalTemp.setValidcounts(activeTemp.getValidcounts());
						}
					}
				}
				if (paymentList.size() > 0) {
					for (StatDeviceInfo paymentTemp : paymentList) {
						if (String.valueOf(totalTemp.getDevicetype()).equals(String.valueOf(paymentTemp.getDevicetype()))) {
							totalTemp.setPaycounts(paymentTemp.getPaycounts());
						}
					}
				}
			}
		}
		return totalList;
	}
	
	
	@Override
	public List<StatDeviceInfo> statTotalDeviceByDate(ParamForm paramForm) {
		if(paramForm.getUserid() != null){
			paramForm.setOrgan(true);
		}
		return workspacedao.statDevicelistByDate(paramForm);
	}
	
	@Override
	public List<StatDeviceInfo> statPaylistByDate(ParamForm paramForm) {
		if(paramForm.getUserid() != null){
			Integer countNum = authOrganDataService.countByUserId((paramForm.getUserid()));
			if(countNum != null && countNum > 0){
				paramForm.setOrgan(true);
			}
		}
		return workspacedao.statPaylistByDate(paramForm);
	}
	/**
	 * <p>Title: getcountByRegion</p>
	 * <p> 功能描述:获取学校统计列表 </p>
	 * @param paramForm
	 * @return
	 */
	@Override
	public List<WorkSpaceVO> getcountByRegion(ParamForm paramForm) {
		List<WorkSpaceVO> workSpaceList = new ArrayList<>();
		List<Schoolinfo> schoolList = 
			getSchoolsByRegion(paramForm.getProvince(),paramForm.getCity(),paramForm.getTown(),paramForm.getUserid());
		if (schoolList.size() == 0) {
			return workSpaceList;
		}
		if(StringUtils.isNotBlank(paramForm.getEndtime())) {
			paramForm.setEndtime(String.format("%s 23:59:59", paramForm.getEndtime().split("[ ]")[0]));
		}
		Map<String,Object> map = new HashMap<>();
		map.put("starttime", paramForm.getStarttime());
		map.put("endtime", paramForm.getEndtime());
		map.put("province", paramForm.getProvince());
		map.put("city", paramForm.getCity());
		map.put("town", paramForm.getTown());
		SchoolDiscounts schoolDiscount = null;
		WorkSpaceVO workspace = null;
		List<StatDeviceInfo> cardSendList = workspacedao.getCardSendCounts(map);
		List<StatDeviceInfo> cardValidList = workspacedao.getCardValidCounts(map);
		List<StatDeviceInfo> deviceSendList = workspacedao.getDeviceSendCounts(map);
		List<StatDeviceInfo> deviceValidList = workspacedao.getDeviceValidCounts(map);
		List<StatDeviceInfo> devicePayList = workspacedao.getDevicePayCounts(map);
		for (Schoolinfo schoolInfo : schoolList) {
			workspace = new WorkSpaceVO();
			//查询当前学校是否有促销
			schoolDiscount = getSchoolDiscountBySchool(schoolInfo.getId());
			if (schoolDiscount != null) {
				workspace.setDiscounttime(new StringBuilder()
						.append(DateUtil.formatDateToString(schoolDiscount.getStarttime(), "yyyy.MM.dd"))
						.append("-")
						.append(DateUtil.formatDateToString(schoolDiscount.getEndtime(), "yyyy.MM.dd")).toString());
			}
			workspace.setSchoolname(schoolInfo.getSchoolname());
			workspace.setProvince(schoolInfo.getProvince());
			workspace.setCity(schoolInfo.getCity());
			workspace.setTown(schoolInfo.getTown());
			//考勤卡发放量
			if (cardSendList.size() > 0) {
				for (StatDeviceInfo deviceInfo : cardSendList) {
					if (schoolInfo.getSchoolname().equals(deviceInfo.getSchoolname())) {
						if (deviceInfo.getDevicetype() != null && deviceInfo.getDevicetype() == 8) {
							workspace.setDevicetypename("13.56");
						}else if (deviceInfo.getDevicetype() != null && deviceInfo.getDevicetype() == 9) {
							workspace.setDevicetypename("2.4");
						}
						workspace.setCardsendcounts(deviceInfo.getCardsendcounts());
					}
				}
			}
			//考勤卡激活量
			if (cardValidList.size() > 0) {
				for (StatDeviceInfo deviceInfo : cardValidList) {
					if (schoolInfo.getSchoolname().equals(deviceInfo.getSchoolname())) {
						workspace.setCardvalidcounts(deviceInfo.getCardvalidcounts());
					}
				}
			}
			//学生证发放量
			if (deviceSendList.size() > 0) {
				for (StatDeviceInfo deviceInfo : deviceSendList) {
					if (schoolInfo.getSchoolname().equals(deviceInfo.getSchoolname())) {
						workspace.setDevicesendcounts(deviceInfo.getDevicesendcounts());
					}
				}
			}
			//学生证激活量
			if (deviceValidList.size() > 0) {
				for (StatDeviceInfo deviceInfo : deviceValidList) {
					if (schoolInfo.getSchoolname().equals(deviceInfo.getSchoolname())) {
						workspace.setDevicevalidcounts(deviceInfo.getDevicevalidcounts());
					}
				}
			}
			//学生证缴费量
			if (devicePayList.size() > 0) {
				for (StatDeviceInfo deviceInfo : devicePayList) {
					if (schoolInfo.getSchoolname().equals(deviceInfo.getSchoolname())) {
						workspace.setDevicepaycounts(deviceInfo.getDevicepaycounts());
					}
				}
			}
			workSpaceList.add(workspace);
		}
		return workSpaceList;
	}
	
	private SchoolDiscounts getSchoolDiscountBySchool(Integer schoolId) {
		SchoolDiscountsExample schoolDiscountsExample = new SchoolDiscountsExample();
		schoolDiscountsExample.createCriteria().andSchoolidEqualTo(schoolId);
		List<SchoolDiscounts> schoolDiscountList = schoolDiscountsMapper.selectByExample(schoolDiscountsExample);
		
		return schoolDiscountList.size() > 0 ? schoolDiscountList.get(0) : null;
	}
	
	private List<Schoolinfo> getSchoolsByRegion(String province,String city,String town,Long userId) {
		if (userId != null) {
			Map<String,Object> map = new HashMap<>();
			map.put("province", province);
			map.put("city", city);
			map.put("town", town);
			map.put("userId", userId);
			return authUserDataDao.getSchoolsByUserId(map);
		}else {
			SchoolinfoExample schoolinfoExample = new SchoolinfoExample();
			Criteria criteria = schoolinfoExample.createCriteria();
			if (StringUtil.isNotEmpty(province)) {
				criteria.andProvinceEqualTo(province);
			}
			if (StringUtil.isNotEmpty(city)) {
				criteria.andCityEqualTo(city);
			}
			if (StringUtil.isNotEmpty(town)) {
				criteria.andTownEqualTo(town);
			}
			return schoolinfoMapper.selectByExample(schoolinfoExample);
		}
	}


	@Override
	public List<WorkSpaceVO> getClassCountsBySchool(ParamForm paramForm) {
		if (StringUtil.isEmpty(paramForm.getSchoolname())) {
			throw new OpServiceException("学校不能为空");
		}
		SchoolinfoExample schoolinfoExample = new SchoolinfoExample();
		schoolinfoExample.createCriteria().andSchoolnameEqualTo(paramForm.getSchoolname());
		List<Schoolinfo> schoolList = schoolinfoMapper.selectByExample(schoolinfoExample);
		if (schoolList.size() == 0) {
			throw new OpServiceException("学校不存在");
		}
		Schoolinfo schoolInfo = schoolList.get(0);
		if (paramForm.getUserid() != null) {
			Map<String,Object> map = new HashMap<>();
			map.put("schoolId", schoolInfo.getId());
			map.put("userId", paramForm.getUserid());
			List<Schoolinfo> schools = authUserDataDao.getSchoolsByUserId(map);
			if (schools.size() == 0) {
				throw new OpServiceException("您没有权限访问当前学校");
			}
		}
		List<WorkSpaceVO> workSpaceList = new ArrayList<>();
		List<StdTeacherInfo> teacherList = getClassBySchoolId(schoolInfo.getId());
		if (teacherList.size() == 0) {
			return workSpaceList;
		}
		Map<String,Object> map = new HashMap<>();
		map.put("starttime", paramForm.getStarttime());
		map.put("endtime", paramForm.getEndtime());
		map.put("schoolname", schoolInfo.getSchoolname());
		WorkSpaceVO workspace = null;
		SchoolDiscounts schoolDiscount = null;
		List<StatDeviceInfo> cardValidList = workspacedao.getCardValidCounts(map);
		List<StatDeviceInfo> deviceSendList = workspacedao.getDeviceSendCounts(map);
		List<StatDeviceInfo> deviceValidList = workspacedao.getDeviceValidCounts(map);
		List<StatDeviceInfo> devicePayList = workspacedao.getDevicePayCounts(map);
		for (StdTeacherInfo teacherInfo : teacherList) {
			workspace = new WorkSpaceVO();
			workspace.setSchoolname(schoolInfo.getSchoolname());
			workspace.setClassname(teacherInfo.getClassname());
			workspace.setTeachername(teacherInfo.getTeachername());
			workspace.setTeachertel(teacherInfo.getTelephone());
			//查询当前学校是否有促销
			schoolDiscount = getSchoolDiscountBySchool(schoolInfo.getId());
			if (schoolDiscount != null) {
				workspace.setDiscounttime(new StringBuilder()
						.append(DateUtil.formatDateToString(schoolDiscount.getStarttime(), "yyyy.MM.dd"))
						.append("-")
						.append(DateUtil.formatDateToString(schoolDiscount.getEndtime(), "yyyy.MM.dd")).toString());
			}
			//考勤卡发放量
			workspace.setCardsendcounts(teacherInfo.getCount());
			//考勤卡激活量
			if (cardValidList.size() > 0) {
				for (StatDeviceInfo deviceInfo : cardValidList) {
					if (teacherInfo.getClassname().equals(deviceInfo.getClassname())) {
						workspace.setCardvalidcounts(deviceInfo.getCardvalidcounts());
					}
				}
			}
			//学生证发放量
			if (deviceSendList.size() > 0) {
				for (StatDeviceInfo deviceInfo : deviceSendList) {
					if (teacherInfo.getClassname().equals(deviceInfo.getClassname())) {
						workspace.setDevicesendcounts(deviceInfo.getDevicesendcounts());
					}
				}
			}
			//学生证激活量
			if (deviceValidList.size() > 0) {
				for (StatDeviceInfo deviceInfo : deviceValidList) {
					if (teacherInfo.getClassname().equals(deviceInfo.getClassname())) {
						workspace.setDevicevalidcounts(deviceInfo.getDevicevalidcounts());
					}
				}
			}
			//学生证缴费量
			if (devicePayList.size() > 0) {
				for (StatDeviceInfo deviceInfo : devicePayList) {
					if (teacherInfo.getClassname().equals(deviceInfo.getClassname())) {
						workspace.setDevicepaycounts(deviceInfo.getDevicepaycounts());
					}
				}
			}
			workSpaceList.add(workspace);
		}
		
		if(paramForm.getSortstatus() != null) {
			workSpaceList = sortList(workSpaceList,paramForm.getSortstatus());
		}
		return workSpaceList;
	}
	/**
	 * 排序
	 * @param workSpaceList
	 * @param sortStatus
	 * @return
	 */
	private List<WorkSpaceVO> sortList(List<WorkSpaceVO> workSpaceList,Integer sortStatus) {
		switch(sortStatus) {
		case 1:
			workSpaceList = (List<WorkSpaceVO>) SortListUtil.sort(workSpaceList, "cardvalidcounts", SortListUtil.ASC);
			break;
		case 2:
			workSpaceList = (List<WorkSpaceVO>) SortListUtil.sort(workSpaceList, "cardvalidcounts", SortListUtil.DESC);
			break;
		case 3:
			workSpaceList = (List<WorkSpaceVO>) SortListUtil.sort(workSpaceList, "devicepaycounts", SortListUtil.ASC);
			break;
		case 4:
			workSpaceList = (List<WorkSpaceVO>) SortListUtil.sort(workSpaceList, "devicepaycounts", SortListUtil.DESC);
			break;
		case 5:
			workSpaceList = (List<WorkSpaceVO>) SortListUtil.sort(workSpaceList, "devicevalidcounts", SortListUtil.ASC);
			break;
		case 6:
			workSpaceList = (List<WorkSpaceVO>) SortListUtil.sort(workSpaceList, "devicevalidcounts", SortListUtil.DESC);
			break;
		}
		return workSpaceList;
	}
	
	private List<StdTeacherInfo> getClassBySchoolId(Integer schoolId) {
		StdTeacherInfoExample stdTeacherInfoExample = new StdTeacherInfoExample();
		stdTeacherInfoExample.createCriteria().andSchoolidEqualTo(schoolId);
		return stdTeacherInfoMapper.selectByExample(stdTeacherInfoExample);
	}
	
}
